/**
 *
 */
package rgbos.forum.webClient;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Vector;

import rgbos.forum.domain.Post;
import rgbos.forum.domain.Topic;
import rgbos.forum.search.AbstractSearchEngine;
import rgbos.forum.search.PostRate;
import rgbos.forum.search.SearchEngine;

import jaxcent.HtmlDiv;
import jaxcent.HtmlElement;
import jaxcent.HtmlImage;
import jaxcent.HtmlInputSubmit;
import jaxcent.HtmlInputText;
import jaxcent.HtmlListElement;
import jaxcent.HtmlOption;
import jaxcent.HtmlPara;
import jaxcent.HtmlSelect;
import jaxcent.HtmlTable;
import jaxcent.HtmlTableCell;
import jaxcent.HtmlTableRow;
import jaxcent.HtmlTextArea;
import jaxcent.JaxcentPage;
import jaxcent.Jaxception;


/**
 * @author Ofir Dagan
 *
 */
public class Search extends JaxcentPage {

	private HtmlPara para = new HtmlPara(this, "header");
	private HtmlDiv loadingDiv_ = new HtmlDiv(this, "loading");
	private HtmlPara footpara_ = new HtmlPara(this,"footerPara");

	private HtmlTableRow row1 = new HtmlTableRow(this, "byContent");
	private HtmlTableRow row2 = new HtmlTableRow(this, "byAuthor");
	private HtmlTableRow row3 = new HtmlTableRow(this, "byDay");
	private HtmlTableRow row4 = new HtmlTableRow(this, "byDays");
	private HtmlTextArea content = new HtmlTextArea(this, "contentText");
	private HtmlInputText author = new HtmlInputText(this, "authorText");
	private HtmlInputText date1 = new HtmlInputText(this, "date1");
	private HtmlInputText date2 = new HtmlInputText(this, "date2");
	private HtmlInputText date3 = new HtmlInputText(this, "date3");
	
	private HtmlSelect searchChooser_ = new HtmlSelect(this, "searchChooser") {
		protected void onChange(String value) {
			if (value.contentEquals("content")) {
				try {
					row1.setStyle("display", "block");
					row2.setStyle("display", "none");
					author.setValue("");
					row3.setStyle("display", "none");
					date1.setValue("");
					row4.setStyle("display", "none");
					date2.setValue("");
					date3.setValue("");
				} catch (Jaxception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			else if (value.contentEquals("author")) {
				try {
					row1.setStyle("display", "none");
					content.setValue("");
					row2.setStyle("display", "block");					
					row3.setStyle("display", "none");
					date1.setValue("");
					row4.setStyle("display", "none");
					date2.setValue("");
					date3.setValue("");				} catch (Jaxception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			else if (value.contentEquals("oneDay")) {
				try {
					row1.setStyle("display", "none");
					content.setValue("");
					row2.setStyle("display", "none");
					author.setValue("");
					row3.setStyle("display", "block");					
					row4.setStyle("display", "none");
					date2.setValue("");
					date3.setValue("");
				} catch (Jaxception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			else if (value.contentEquals("rangeDay")) {
				try {
					row1.setStyle("display", "none");
					content.setValue("");
					row2.setStyle("display", "none");
					author.setValue("");
					row3.setStyle("display", "none");
					date1.setValue("");
					row4.setStyle("display", "block");
				} catch (Jaxception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	};
	
	private WebClientHandler handler_ = WebClientHandler.getWebClientHandler();
	private AbstractSearchEngine sEengine_ = handler_.getSearchEngine();
	private Vector<PostRate> postVec;
//	private HtmlTable searchTable = new HtmlTable(this,"searchTable");
	private HtmlTable table = new HtmlTable(this,"postTable");
	private DateFormat df_ = new SimpleDateFormat("dd/MM/yyyy");
	
	private final JaxcentPage page = this;
	
	private HtmlInputSubmit submitButton = new HtmlInputSubmit(this, "submit") {
		protected void onClick( Map pageData ) {
			String byContent = (String) pageData.get("byContent");
			String byAuthor = (String) pageData.get("byAuthor");
			String byDate= (String)pageData.get("date1");
			String byDateFrom= (String)pageData.get("date2");
			String byDateTo= (String)pageData.get("date3");
			if(checkLegalInput(byContent,byAuthor,byDate,byDateTo,byDateFrom)){
				if(!byContent.equals("")){
					postVec=sEengine_.searchByContent(handler_.escape(byContent));
				}else if(!byAuthor.equals("")){
					postVec=sEengine_.searchByAuthor(byAuthor);
				}else if(!byDate.equals("")){
					DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
					try {
						Date d = df.parse(byDate);
						if (!df.format(d).contentEquals(byDate)) {
							showMessageDialog("The date is not in the right format, please choose the date using the provided calander");
							return;
						}
					} catch (ParseException e) {
						showMessageDialog("The date is not in the right format, please choose the date using the provided calander");
						return;
					}
					postVec=sEengine_.searchByDate(byDate);
				}else{
					DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
					try {
						Date d = df.parse(byDateFrom);
						Date d2 = df.parse(byDateTo);
						if (!df.format(d).contentEquals(byDateFrom) | !df.format(d2).contentEquals(byDateTo)) {
							showMessageDialog("The date is not in the right format, please choose the date using the provided calander");
							return;
						}
					} catch (ParseException e) {					
						showMessageDialog("The date is not in the right format, please choose the date using the provided calander");
						return;
					}
					postVec=sEengine_.searchByDate(byDateFrom, byDateTo);
				}
				try {						
					table.deleteAllRows();
					table.setStyle("display", "none");
					loadingDiv_.setStyle("display", "block");
					int i = showPostsTable(postVec);
					if (i == 0) {
						String[] row = {"<p><center>Search returned no results</center></p><br>"};
						HtmlTableRow htmlRow = table.insertRow(0, row);
						HtmlTableCell htmlCell = new HtmlTableCell(page, htmlRow, 0);
						htmlCell.setWidth("750");
					}
					loadingDiv_.setStyle("display", "none");
					table.setStyle("display", "block");
			} catch (Jaxception e) {
					e.printStackTrace();
				}
			}

		}

		private boolean checkLegalInput(String byContent, String byAuthor,
				String byDate, String byDateTo, String byDateFrom) {
			int count=0;
			if(!byContent.equals(""))
				count++;
			if(!byAuthor.equals(""))
				count++;
			if(!byDate.equals(""))
				count++;
			if(!byDateTo.equals(""))
				count++;
			if(!byDateFrom.equals(""))
				count++;
			if(count==0){
				showMessageDialog("Please fill in one of the search options.");
			}else if(count==1){
				return true;
			}else if(count>1){
				if(count==2 && !byDateTo.equals("") && !byDateFrom.equals("")){
					Date d;
					Date d2;
					try {
						DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
						d = df.parse(byDateFrom);
						d2 = df.parse(byDateTo);
						if(d.after(d2)){
							showMessageDialog("The From date is later than the To Date");
						}else{
							return true;
						}
					} catch (ParseException e) {
						showMessageDialog("The date is not in the right format, please choose the date using the provided calander");
					}															
				}else{
					showMessageDialog("Please fill just one search option.");
				}
			}
			return false;
		}
	};

	public Search(){
		super();		
	}

	protected void onUnload() {
		try {
			Map sessionData = getAllSessionData(false);
			handler_.unload(sessionData);			
		} catch (Jaxception e) {
			e.printStackTrace();
		}
	}

	protected void onLoad() {
		try {									
			table.setCssClass("postTable");
			table.setStyle("width", "750px");
			table.setStyle("max-width", "750px");
			searchChooser_.setSelectedIndex(0);
			setFormSaveEnabled(false);
			submitButton.setValue("Search");
			Map sessionData = getAllSessionData( false );
			handler_.DisplayHeader(para, sessionData, this); //must be before display footer!
			handler_.displayFooter(footpara_, sessionData, this);			
		} catch (Jaxception e) {
			e.printStackTrace();
		}
	}
	
	private int showPostsTable(Vector<PostRate> postVec) {
		int i;
		for (i=0; i < postVec.size(); i++) {
			final Post p = postVec.elementAt(i).getPost();
			String[] row=new String[1];
			try {						
				row[0] = handler_.unescape(p.getTitle_());												
				HtmlTableRow htmlRow1 = table.insertRow(i*5,row);
				
				HtmlTableCell htmlCell1 = new HtmlTableCell(this, htmlRow1, 0);
				htmlCell1.setCssClass("postHeader");
				htmlCell1.setWidth("750");
				htmlCell1.setColSpan(2);
				
				String[] row2 = new String[2];
				row2[0]="<font size=\"2\">Posted by</font><br>"+p.getAuthorName()+"<br>"+p.getDate_();
				String body = p.getBody_();
				if (body == null)
					body = "";
				row2[1]= handler_.unescape(body).replaceAll("\n", "<br>");
				HtmlTableRow htmlRow2 = table.insertRow(i*5+1,row2);
				HtmlTableCell htmlCellLeft = new HtmlTableCell(this, htmlRow2, 0);
				HtmlTableCell htmlCellRight = new HtmlTableCell(this, htmlRow2, 1);
				htmlCellLeft.setCssClass("postLeft");					
				htmlCellRight.setCssClass("postRight");	
				
				Topic top = handler_.getControl().getTopicByPostId(p.getId_());
				String link = "";
				if (top != null)
					link = "<a href=\"/showPosts.html?topicId=" + String.valueOf(top.getId_()) + "\">Click to see the full Topic...</a>";				
				String[] editRow = {"&nbsp;",link};	
				addEditRows(editRow,i);
			} catch (Jaxception e) {
				e.printStackTrace();
			}
		}
		return i;
	}
	
	public void addEditRows(String[] editRow, int i) throws Jaxception {
		HtmlTableRow htmlEditRow = table.insertRow(i*5+3,editRow);
		HtmlTableCell htmlEditCell1 = new HtmlTableCell(this, htmlEditRow, 0);
		HtmlTableCell htmlEditCell2 = new HtmlTableCell(this, htmlEditRow, 1);
		htmlEditCell1.setCssClass("editLeft");
		htmlEditCell2.setCssClass("editRight");
										
		String[] delimeter = {""};								
		HtmlTableRow htmlDelimeterRow = table.insertRow(i*5+4,delimeter);
		HtmlTableCell htmlDelimeterCell1 = new HtmlTableCell(this, htmlDelimeterRow, 0);								
		htmlDelimeterCell1.setCssClass("delimeter");
	}
}
